package cn.ws.oa.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.ws.oa.pojo.Aothority;
import cn.ws.oa.pojo.AothorityAndIs;
import cn.ws.oa.pojo.User;
import cn.ws.oa.service.AothorityService;
import cn.ws.oa.service.RoleAndAothService;
import cn.ws.oa.service.UserService;

@Controller
public class LoginController {
	
	@Autowired
	private UserService userService;
	@Autowired
	private RoleAndAothService roleAndAothService;
	@Autowired
	private AothorityService aothorityService;
	@RequestMapping(value = "/toLogin.action")
	public String toLogin(Model model) {
		return "login";
	}
	
	@RequestMapping(value = "/login.action")
	public String login(User user,Model model,HttpServletRequest request) {
		
		User loginUser=userService.selectUserByNum(user.getUserNum());
		if(loginUser!=null){
			if(user.getUserPassword().equals(loginUser.getUserPassword())) {
				List<Integer> roleAndAothList= roleAndAothService.queryByRoleId(loginUser.getRoleId());
				
				List<Aothority> aothorityList = aothorityService.queryAll();
				Map<String,AothorityAndIs> loginUserAoth = new HashMap<String,AothorityAndIs>();
				
				for(int i=0;i<aothorityList.size();i++) {
					AothorityAndIs aothorityAndIs=new AothorityAndIs();
					Aothority aothority = aothorityList.get(i);
					aothorityAndIs.setAothority(aothority);
					if(roleAndAothList.contains(aothorityList.get(i).getAothorityId())) {
						aothorityAndIs.setIsChecked(1);
					}else {
						aothorityAndIs.setIsChecked(-1);
					}
					loginUserAoth.put(aothorityList.get(i).getAothorityId()+"",aothorityAndIs);
				}
				request.getSession().setAttribute("loginUserAoth", loginUserAoth);
				
				//System.out.println(loginUserAoth.get("2").getIsChecked());
				
				request.getSession().setAttribute("loginUser", loginUser);
				return "index";
			}else {
				model.addAttribute("msg2","密码错误");
				return "login";
			}
		}else {
			model.addAttribute("msg1","账号不存在");
			return "login";
		}
	}
	@RequestMapping(value = "/exit.action")
	public String exit(User loginUser,Model model,HttpServletRequest request) {
		request.getSession().removeAttribute("loginUser");
		return "login";
	}
}
